package db;

import java.sql.SQLException;
import java.util.ArrayList;



public class DbTableModel implements DbTableModelInterface {
	protected int id;
	
	//cheia primara din tabela
	protected String _pramary;
	
	//den coloanelor din tabela
	protected String[] _optionsName=null;
	
	//valorile corespunzatoare coloanelo date
	protected Object[] _options=null;
	
	protected DbTable mapper = null;
	
	public DbTableModel() {
		_setModel();
	}

	public static DbTableModelInterface find(DbTableModel t, int index) throws SQLException {

		System.out.println(t.mapper);
		
		DbSelect select = (DbSelect) t.mapper.select();
		select.where(t._pramary + "=" + index);

		ArrayList list = (ArrayList) t.mapper.fetchAll(select);

		if (list.size() == 0) {
			return null;
		}
		DbRow row = (DbRow) list.get(0);

		int n = row.getSize();
		t._options = new Object[n];
		t._optionsName = new String[n];
		for (int i = 0; i < n; i++) {
			t._options[i] = row.getColomn(i);
			t._optionsName[i] = row.getColumnName(i);

		}
		t.id = index;

		return t;
		

	}

	protected void _setModel() {
		mapper = null;
	}

	@Override
	public void save() throws SQLException {
		DbRow rw;
		if(id>0) {
			rw = new DbRow(_options.length);
			for (int i = 0; i < _options.length; i++) {
				rw.setRow(_options[i].toString(), i, _optionsName[i]);
			}
			mapper.update(rw, _pramary + "=" + id);
		} else {
			rw = new DbRow(_optionsName.length-1);
			int j = 0;
			for (int i = 0; i < _optionsName.length; i++) {
				if (!_optionsName[i].toString().equals(_pramary)) {
					rw.setRow(_options[i].toString(), j, _optionsName[i]);
					j++;
				} 
				
			}
			mapper.insert(rw);
		}
		

	}

	@Override
	public void setOptions(Object data, String option) {
		for (int i = 0; i < _optionsName.length; i++) {
			if(_optionsName[i].equals(option)) {
				_options[i] = data;
			}
		}
		
	}

}
